package com.frontop.terminal.timer;

import cn.hutool.http.HttpRequest;
import com.frontop.terminal.constant.InterfaceConst;
import com.frontop.terminal.entity.AwaitInform;
import com.frontop.terminal.enums.HeaderEnum;
import com.frontop.terminal.util.ReadDataUtil;
import com.frontop.terminal.util.WriteDataUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 通知服务器同步资源发布状态定时器
 * </P>
 *
 * @author :CCC
 * @since :2021-07-02 11:16:00
 **/
@Component
@Slf4j
@RequiredArgsConstructor
public class AwaitInformTimer {

    @Scheduled(cron = "*/60 * * * * ?")
    private void service() {
        List<AwaitInform> awaitInformList = ReadDataUtil.getAwaitInform();
        if (Objects.nonNull(awaitInformList) && !awaitInformList.isEmpty()) {

            Iterator<AwaitInform> iterator = awaitInformList.iterator();
            String url = ReadDataUtil.getTerminalConfig().getServerAddress() + InterfaceConst.DOWNLOAD_RESOURCE_SUCCESS;

            while (iterator.hasNext()) {
                AwaitInform awaitInform = iterator.next();
                boolean requestStatus = false;

                try {
                    requestStatus = HttpRequest.post(url)
                            .header(HeaderEnum.TERMINAL_TOKEN.getKey(), ReadDataUtil.getTerminalConfig().getAuthorizationCode())
                            .form("mac", awaitInform.getMac())
                            .form("id", awaitInform.getMediaId())
                            .execute()
                            .isOk();

                } catch (Exception ignored) {
                }

                //通知成功删除记录
                if (requestStatus) {
                    iterator.remove();
                } else {
                    log.warn("[定时器]通知服务器同步资源发布状态时请求失败,将稍后重试.\t媒体ID:" + awaitInform.getMediaId());
                }
            }

            //保存本地
            WriteDataUtil.write(awaitInformList, ReadDataUtil.AWAITINFORM_LIST_CODING);
        }
    }
}
